package com.suliao.common.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @program: suliao
 * @description:阿里云短信服务：注意：需要 签名名称、模版CODE 以及 RAM访问控制中的 AccessKeyID 和 AccessKeySecret
 * @author: Yang-Teng-Fei
 * @create: 2020-05-19 15:18
 **/
@Component
@Slf4j
public class SMSUtil {

    //产品名称:云通信短信API产品,开发者无需替换
    @Value("${aliyun.sms.product:Dysmsapi}")
    private String product;

    //产品域名,开发者无需替换
    @Value("${aliyun.sms.domain:dysmsapi.aliyuncs.com}")
    private String domain;

    // 此处需要替换成开发者自己的AK
    @Value("${aliyun.sms.access-key-id:LTAI4GEsPKXcnoopQRRvD1Bz}")
    private String accessKeyId;

    @Value("${aliyun.sms.access-key-secret:OUOFEL8aBkcBzoZ1qPEvyyMblecdf1}")
    private String accessKeySecret;

    //连接超时时间
    @Value("${aliyun.sms.connect-timeout:10000}")
    private String connectTimeout;

    //读取超时时间
    @Value("${aliyun.sms.read-timeout:10000}")
    private String readTimeout;

    //短信签名
    @Value("${aliyun.sms.sign-name:塑料产业网}")
    private String signName;

    //短信模板
    @Value("${aliyun.sms.template-code:SMS_188860592}")
    private String templateCode;

    //业务方扩展字段
    @Value("${aliyun.sms.out-id:yourOutId}")
    private String outId;

    /**
     * 发送短信1
     *
     * @param telephone
     * @return
     */
    public SendSmsResponse sendSms(String telephone) {
        SendSmsResponse sendSmsResponse = null;
        try {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", connectTimeout);
            System.setProperty("sun.net.client.defaultReadTimeout", readTimeout);
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(telephone);
            //必填:短信签名
            request.setSignName(signName);
            //必填:短信模板
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam("{\"code\":\"" + getMsgCode() + "\"}");
            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId(outId);
            //hint 此处可能会抛出异常，注意catch
            sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                log.info("短信发送成功！");
            } else {
                log.info("短信发送失败！");
            }
        } catch (ClientException ce) {
            ce.printStackTrace();
            log.error("Error Message" + ce.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Error Message: " + e.getMessage());
        }
        return sendSmsResponse;
    }

    /**
     * 发送短信2
     *
     * @param telephone
     * @return
     */
    public Map<String, SendSmsResponse> sendSMS(String telephone) {
        HashMap result = null;
        try {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", connectTimeout);
            System.setProperty("sun.net.client.defaultReadTimeout", readTimeout);
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(telephone);
            //必填:短信签名
            request.setSignName(signName);
            //必填:短信模板
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            String msgCode = getMsgCode();
            request.setTemplateParam("{\"code\":\"" + msgCode + "\"}");
            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId(outId);
            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                log.info("短信发送成功！");
            } else {
                log.info("短信发送失败！");
            }
            result = new HashMap<String, SendSmsResponse>();
            result.put(msgCode, sendSmsResponse);
        } catch (ClientException ce) {
            ce.printStackTrace();
            log.error("Error Message" + ce.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Error Message: " + e.getMessage());
        }
        return result;
    }

    /**
     * 生成验证码
     *
     * @return
     */
    private String getMsgCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }
}
